﻿using System;
using Script.Framework;
using Script.Scene.Msg;
using UnityEngine.SceneManagement;

namespace Script.Scene
{
    /// <summary>
    /// 场景管理器
    /// </summary>
    public class SceneMgr : ManagerBase
    {
        public static SceneMgr instance;

        private void Awake()
        {
            instance = this;

            SceneManager.sceneLoaded += SceneManager_sceneLoaded;

            Add(SceneEvent.LOAD_SCENE, this);
        }


        public override void Execute(int eventCode, object message)
        {
            switch (eventCode)
            {
                case SceneEvent.LOAD_SCENE:
                    LoadSceneMsg sceneIndex = message as LoadSceneMsg;
                    LoadScene(sceneIndex);
                    break;
            }
        }

        /// <summary>
        /// 临时变量
        /// </summary>
        private Action onSceneLoaded;

        /// <summary>
        /// 加载场景
        /// </summary>
        private void LoadScene(LoadSceneMsg sceneMsg)
        {
            if (sceneMsg.SceneBuildIndex != -1)
            {
                SceneManager.LoadScene(sceneMsg.SceneBuildIndex);
            }

            if (sceneMsg.SceneBuildName != null)
            {
                SceneManager.LoadScene(sceneMsg.SceneBuildName);
            }

            if (sceneMsg.OnSceneLoaded != null)
            {
                onSceneLoaded = sceneMsg.OnSceneLoaded;
            }
        }


        /// <summary>
        /// 当场景加载完成的时候调用
        /// </summary>
        private void SceneManager_sceneLoaded(UnityEngine.SceneManagement.Scene scene, LoadSceneMode loadSceneMode)
        {
            if (onSceneLoaded != null)
            {
                onSceneLoaded();

                onSceneLoaded = null;
            }
        }
    }
}